// pages/conversation/conversation.js
const app = getApp();
console.log('getApp available:', typeof getApp !== 'undefined');
Page({
  data: {
    conversationID: '',
    unionID: '',
    messages: [],
    inputValue: '',
    showMapPopup: false,
    showPathPopup: true,
    conversation: { title: '学习导航', map: [], learning_path: [] },
    isLoading: false,
    showHintPopup: false,
    learningPaths: [],
    isMember: false,
    scrollToMessageId: '',
    showAllQuestionsPopup: false,
    userRole: '',
    isNewUser: false,
    showInitialPath: true,
    estimatedTime: 30,
    subject: '',
    subjectDisplay: '', // 新增：学科显示名称
    masteryStatus: {} // 新增：掌握状态
  },

  onLoad(options) {
    console.log('App instance:', app.globalData);
    const unionID = wx.getStorageSync('unionID') || '';
    const conversationID = options.conversationID || wx.getStorageSync('selectedConversationID') || '';
    const userRole = app.globalData.userInfo?.role || wx.getStorageSync('role') || 'lifelong_learner';
  
    console.log('conversation onLoad:', { options, conversationID });
  
    this.setData({
      unionID,
      conversationID,
      userRole,
      messages: [] // 清空消息，防止显示旧数据
    });
  
    // 确保分享菜单显示
    wx.showShareMenu({
      menus: ['shareAppMessage', 'shareTimeline']
    });
  
    // 如果 conversationID 以 "expert" 开头，跳转
    if (conversationID && conversationID.startsWith('expert')) {
      this.navigateToExpertConversation(conversationID);
      return;
    }
  
    // 仅在非专家路径时设置 lastPage
    wx.setStorageSync('lastPage', 'conversation');
  
    // 加载普通对话
    if (unionID && conversationID) {
      this.loadConversation();
    }
  },
  
  onShow() {
    const unionID = wx.getStorageSync('unionID') || '';
    const storedConversationID = wx.getStorageSync('selectedConversationID') || '';
    const lastPage = wx.getStorageSync('lastPage') || '';
  
    console.log('conversation onShow:', {
      unionID,
      storedConversationID,
      lastPage,
      currentConversationID: this.data.conversationID
    });
  
    // 清空消息，防止显示旧数据
    this.setData({ messages: [] });
  
    // 如果 storedConversationID 存在且以 "expert" 开头，跳转到专家路径
    if (storedConversationID && storedConversationID.startsWith('expert')) {
      console.log('检测到专家路径 conversationID，跳转到 expertConversation');
      this.navigateToExpertConversation(storedConversationID);
      return;
    }
  
    // 更新数据并加载普通对话
    this.setData({
      unionID,
      conversationID: this.data.conversationID || storedConversationID
    });
  
    if (unionID && this.data.conversationID) {
      console.log('加载普通对话:', this.data.conversationID);
      this.loadConversation();
    } else {
      console.log('缺少 unionID 或 conversationID，跳转到历史记录页');
      wx.navigateTo({ url: '/pages/conversationHistory/conversationHistory' });
    }
  },
  
  navigateToExpertConversation(conversationID, retryCount = 1) {
    // 记录导航尝试
    console.log('尝试导航到 expertConversation:', { conversationID, retryCount });
  
    // 检查导航堆栈
    const pages = getCurrentPages();
    console.log('当前导航堆栈:', pages.map(page => page.route));
  
    // 如果 retryCount 为 0，使用 reLaunch 清理堆栈
    if (retryCount === 0) {
      wx.reLaunch({
        url: `/pages/expertPath/expertConversation/expertConversation?pathID=${conversationID}`,
        success: () => {
          console.log('reLaunch 到 expertConversation 成功');
        },
        fail: (err) => {
          console.error('reLaunch 到 expertConversation 失败:', err);
          wx.showToast({ title: '加载专家路径失败，请稍后重试', icon: 'none' });
          wx.navigateTo({ url: '/pages/conversationHistory/conversationHistory' });
          wx.removeStorageSync('selectedConversationID');
        }
      });
      return;
    }
  
    // 尝试 navigateTo
    wx.showLoading({ title: '跳转中...' });
    wx.navigateTo({
      url: `/pages/expertPath/expertConversation/expertConversation?pathID=${conversationID}`,
      success: () => {
        console.log('跳转到 expertConversation 成功');
      },
      fail: (err) => {
        console.error('跳转到 expertConversation 失败:', err);
        // 重试一次
        if (retryCount > 0) {
          setTimeout(() => {
            console.log('重试导航到 expertConversation:', { conversationID, retryCount: retryCount - 1 });
            this.navigateToExpertConversation(conversationID, retryCount - 1);
          }, 1000);
        } else {
          wx.showToast({ title: '加载专家路径失败，请稍后重试', icon: 'none' });
          wx.navigateTo({ url: '/pages/conversationHistory/conversationHistory' });
          wx.removeStorageSync('selectedConversationID');
        }
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  },
  
  continueOnShow(unionID, storedConversationID, userRole) {
    // 验证 storedConversationID
    if (storedConversationID && storedConversationID !== this.data.conversationID && !storedConversationID.startsWith('expert')) {
      this.setData({
        conversationID: storedConversationID,
        messages: [],
        showInitialPath: true
      });
      this.loadConversation();
    }
  
    if (userRole !== this.data.userRole) {
      this.setData({ userRole });
    }
  
    this.setData({
      unionID: unionID,
      conversationID: this.data.conversationID || storedConversationID,
      userRole: userRole
    });
  
    if (!unionID) {
      console.log('conversation onShow: unionID 为空，尝试静默登录');
      app.doAutoLogin()
        .then(() => {
          this.setData({ unionID: wx.getStorageSync('unionID') });
          this.checkNewUser();
        })
        .catch((err) => {
          console.error('静默登录失败:', err);
          this.checkNewUser();
        });
    } else {
      this.checkNewUser();
    }
  },
  
  loadConversation() {
    if (!this.data.conversationID || !this.data.unionID) {
      wx.showToast({ title: '缺少必要参数', icon: 'none' });
      return;
    }
  
    // 防止加载专家路径 conversationID
    if (this.data.conversationID.startsWith('expert')) {
      console.warn('尝试加载专家路径 conversationID，强制跳转:', this.data.conversationID);
      this.navigateToExpertConversation(this.data.conversationID);
      return;
    }
  
    wx.showLoading({ title: '加载中...' });
    const baseUrl = getApp().getApiBaseUrl();
    wx.request({
      url: `${baseUrl}/conversation/get?conversationID=${this.data.conversationID}&unionID=${this.data.unionID}`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${wx.getStorageSync('jwt_token')}`,
        'Content-Type': 'application/json'
      },
      success: (res) => {
        wx.hideLoading();
        //console.log('loadConversation response:', JSON.stringify(res.data, null, 2));
        if (res.statusCode === 200 && res.data.success && res.data.conversation) {
          const conversation = res.data.conversation;
          const messages = (res.data.messages || []).map((message, index) => {
            const messageID = message._id || message.messageID;
            if (!messageID || !/^[0-9a-fA-F]{24}$/.test(messageID)) {
              console.warn(`消息 ${index} 缺少或无效 messageID:`, message);
              return null;
            }
            return {
              ...message,
              messageID: messageID,
              testQuestions: (message.testQuestions || []).map(testQuestion => ({
                ...testQuestion,
                selectedOption: testQuestion.selectedOption || null,
                resultStatus: testQuestion.resultStatus || '',
                feedback: testQuestion.feedback || '',
                isCorrect: testQuestion.isCorrect || false,
              })),
            };
          }).filter(msg => msg !== null);
  
          // 处理学习路径和掌握状态
          const learningPath = conversation.learning_path || [];
          const cleanedPath = learningPath.map(item => item.trim());
          const masteryStatus = res.data.masteryStatus || {};
          const cleanedMasteryStatus = {};
          for (const key in masteryStatus) {
            cleanedMasteryStatus[key.trim()] = masteryStatus[key];
          }
          cleanedPath.forEach(item => {
            if (!cleanedMasteryStatus[item]) {
              cleanedMasteryStatus[item] = 'untested';
            }
          });
  
          this.setData({
            messages,
            'conversation.title': conversation.title || '学习导航',
            'conversation.learning_path': cleanedPath,
            learningPaths: [cleanedPath],
            scrollToMessageId: '',
            showInitialPath: messages.length === 0,
            subject: conversation.subject || 'general',
            subjectDisplay: this.getSubjectDisplay(conversation.subject || 'general'),
            masteryStatus: cleanedMasteryStatus
          });
          console.log('Loaded messages:', messages);
          if (messages.length === 0 && res.data.messages.length > 0) {
            console.error('所有消息因缺少有效 messageID 被过滤', res.data.messages);
            wx.showModal({
              title: '提示',
              content: '无法加载消息，请重试或联系支持',
              confirmText: '重试',
              cancelText: '联系支持',
              success: (res) => {
                if (res.confirm) {
                  this.loadConversation();
                } else {
                  wx.navigateTo({ url: '/pages/support/support' });
                }
              }
            });
          }
          if (!conversation.learning_path || conversation.learning_path.length === 0) {
            this.loadLearningPath();
          } else {
            this.setData({ showPathPopup: true });
          }
          if (messages.length > 0) {
            this.scrollToFirstMessage();
          }
        } else {
          wx.showToast({ title: res.data.detail || '加载失败', icon: 'none' });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.error('加载对话失败:', err);
        wx.showToast({ title: `网络错误: ${err.errMsg}`, icon: 'none' });
      }
    });
  },
  
 

  // 获取学科显示名称
  getSubjectDisplay(subject) {
    const subjectMap = {
      'english': '英语',
      'math': '数学',
      'physics': '物理',
      'chemistry': '化学',
      'biology': '生物',
      'history': '历史',
      'politics': '政治',
      'geography': '地理',
      'chinese': '语文',
      'general': '通用'
    };
    let level = '';
    let sub = subject;
    if (subject.startsWith('zk_')) {
      level = '初中';
      sub = subject.replace('zk_', '');
    } else if (subject.startsWith('gk_')) {
      level = '高中';
      sub = subject.replace('gk_', '');
    }
    const subjectName = subjectMap[sub] || '未知学科';
    return level ? `${level}${subjectName}` : subjectName;
  },

  scrollToFirstMessage() {
    setTimeout(() => {
      if (this.data.messages.length > 0) {
        this.setData({
          scrollToMessageId: 'message-0'
        });
      }
    }, 300);
  },

  showPathPopup() {
    if (this.data.conversation.learning_path && this.data.conversation.learning_path.length > 0) {
      this.setData({
        learningPaths: [this.data.conversation.learning_path],
        showPathPopup: true
      });
    } else {
      this.loadLearningPath();
    }
  },

  hidePathPopup() {
    this.setData({ showPathPopup: false });
  },

  onPathItemClick(e) {
    const selectedItem = e.currentTarget.dataset.item;
    this.setData({
      showInitialPath: false // 点击路径项后隐藏初始路径
    });
    this.handleQuestion(selectedItem);
    this.setData({ showPathPopup: false });
  },

  sendMessage() {
    const input = this.data.inputValue.trim();
    if (!input) {
      wx.showToast({ title: '请输入内容', icon: 'none' });
      return;
    }
    this.setData({
      showInitialPath: false // 输入新消息时也隐藏初始路径
    });
    this.handleQuestion(input);
    this.setData({ inputValue: '' });
  },

  handleInput(e) {
    this.setData({ inputValue: e.detail.value });
  },

  handleQuestion(question) {
    const normalizedQuestion = question.trim().toLowerCase();
    const existingMessageIndex = this.data.messages.findIndex(msg => {
      const normalizedMsgQuestion = msg.question.trim().toLowerCase();
      return normalizedMsgQuestion === normalizedQuestion;
    });

    if (existingMessageIndex !== -1) {
      this.scrollToExistingMessage(existingMessageIndex);
    } else {
      this.sendToServer(question);
    }
  },

  sendToServer(question, isInteractive = false) {
    this.setData({ isLoading: true });
  
    // 输入长度验证（与后端 50 字符限制一致）
    if (question.length > 50) {
      this.setData({ isLoading: false });
      wx.showModal({
        title: '提示',
        content: '输入内容长度不能超过 50 个字符，请缩短后重试',
        confirmText: '好的',
        showCancel: false
      });
      return;
    }
  
    const cleanItem = isInteractive
      ? question.replace(/[^a-zA-Z0-9\u4e00-\u9fff\s,.;:\-\+\*/=()（）《》·]/g, '')
      : question;
  
    if (isInteractive && !cleanItem.trim()) {
      this.setData({ isLoading: false });
      wx.showModal({
        title: '提示',
        content: '知识点内容无效，请尝试其他知识点',
        confirmText: '好的',
        showCancel: false
      });
      return;
    }
  
    const requestData = {
      conversationID: this.data.conversationID,
      unionID: this.data.unionID,
      question: isInteractive ? cleanItem : question
    };
    const baseUrl = getApp().getApiBaseUrl(); 
    wx.request({
      url: `${baseUrl}/conversation/add_message`,
      method: 'POST',
      data: requestData,
      header: {
        'Authorization': `Bearer ${wx.getStorageSync('jwt_token')}`,
        'Content-Type': 'application/json'        
      },
      success: (res) => {
        this.setData({ isLoading: false });
        //console.log('sendToServer response:', JSON.stringify(res.data, null, 2));
        if (res.statusCode === 200 && res.data.success) {
          const newMessageData = res.data.messages && res.data.messages.length > 0 ? res.data.messages[0] : {};
          const messageID = res.data.messageID || newMessageData._id || newMessageData.messageID;
          if (!messageID || !/^[0-9a-fA-F]{24}$/.test(messageID)) {
            console.error('服务器未返回有效 messageID:', res.data);
            wx.showToast({ title: '消息ID无效，无法添加消息', icon: 'none' });
            return;
          }
          const newMessage = {
            messageID: messageID,
            conversationID: this.data.conversationID,
            question: question,
            answer: res.data.answer || '',
            prompts: newMessageData.prompts || { whyItMatters: '', stopAndThink: '' },
            misconception: newMessageData.misconception || '',
            interactiveList: newMessageData.interactiveList || [],
            testQuestions: (newMessageData.testQuestions || []).map(testQuestion => ({
              ...testQuestion,
              selectedOption: null,
              resultStatus: '',
              feedback: '',
              isCorrect: false,
            })),
            recommendedQuestions: newMessageData.recommendedQuestions || []
          };
          const updatedMessages = [...this.data.messages, newMessage];
          this.setData({ messages: updatedMessages });
          console.log('New message added:', newMessage);
          this.scrollToNewMessage(updatedMessages.length - 1);
        } else if (res.statusCode === 400) {
          wx.showModal({
            title: '提示',
            content: res.data.detail || '知识点包含不支持的字符或不在当前学习路径中，仅允许字母、数字、中文、空格、括号（半角 () 和全角（））、逗号（,）、顿号（,）、正斜杠（/）、中点（·）、书名号（《》）等',
            confirmText: '好的',
            showCancel: false
          });
        } else if (res.statusCode === 422 && res.data.detail && res.data.detail.errorCode === 'INPUT_NOT_LEARNING_RELATED') {
          wx.showModal({
            title: '提示',
            content: '请输入与学习有关的问题，或选择学习路径中的知识点',
            confirmText: '好的',
            showCancel: false,
            success: () => {
              this.setData({ showHintPopup: true });
            }
          });
        } else if (res.statusCode === 403) {
          wx.showModal({
            title: '提示',
            content: res.data.detail || '今天的学习额度已用完，升级会员可继续探索！',
            confirmText: '升级会员',
            cancelText: '明天再来',
            success: (modalRes) => {
              if (modalRes.confirm) {
                wx.navigateTo({ url: '/pages/membership-purchase/membership-purchase' });
              }
            }
          });
        } else {
          wx.showToast({ title: res.data.detail || '处理失败，请稍后重试', icon: 'none' });
        }
      },
      fail: (err) => {
        this.setData({ isLoading: false });
        console.error('sendToServer 失败:', err);
        wx.showToast({ title: '网络错误，请稍后重试', icon: 'none' });
      }
    });
  },

  scrollToNewMessage(index) {
    setTimeout(() => {
      this.setData({
        scrollToMessageId: `message-${index}`
      });
    }, 300);
  },

  handleInvitation() {
    const inviterID = wx.getStorageSync('inviterID') || app.globalData.inviterID || '';
    const unionID = this.data.unionID;
    console.log('handleInvitation - inviterID:', inviterID, 'unionID:', unionID);

    if (!inviterID || !unionID || inviterID === unionID) {
      console.log('绑定条件不满足:', { inviterID, unionID });
      return;
    }

    const token = wx.getStorageSync('token') || 0;
    if (token > 10000) {
      console.log('用户已通过邀请获得奖励，token:', token);
      wx.showToast({ title: '已通过邀请获得1万token！', icon: 'success' });
      wx.removeStorageSync('inviterID');
      return;
    }
  },

  checkNewUser() {
    if (!this.data.conversationID && !wx.getStorageSync('role')) {
      this.setData({ isNewUser: true });
      setTimeout(() => {
        wx.navigateTo({
          url: '/pages/role/role',
          success: () => console.log('新用户跳转到 role'),
          fail: (err) => console.error('跳转失败:', err)
        });
      }, 1000);
    } else if (!this.data.conversationID) {
      setTimeout(() => {
        wx.switchTab({
          url: '/pages/index1/index1',
          success: () => console.log('新用户跳转到 index1'),
          fail: (err) => console.error('跳转失败:', err)
        });
      }, 1000);
    } else {
      this.loadConversation();
    }
  },

  loadLearningPath() {
    wx.showLoading({ title: '加载学习路径...' });
    const baseUrl = getApp().getApiBaseUrl();
    wx.request({
      url: `${baseUrl}/learningPath/generate_learning_path`,
      method: 'POST',
      data: {
        unionID: this.data.unionID,
        conversationID: this.data.conversationID
      },
      header: {
        'Authorization': `Bearer ${wx.getStorageSync('jwt_token')}`
      },
      success: (res) => {
        wx.hideLoading();
        if (res.data.success) {
          this.setData({
            learningPaths: [res.data.path],
            'conversation.learning_path': res.data.path,
            showPathPopup: true
          });
        } else {
          wx.showToast({ title: res.data.message || '加载路径失败', icon: 'none' });
          this.setData({ learningPaths: [] });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        wx.showToast({ title: '网络错误', icon: 'none' });
        this.setData({ learningPaths: [] });
      }
    });
  },

  scrollToExistingMessage(index, retryCount = 3) {
    if (retryCount < 0) {
      wx.showToast({ title: '无法滚动到消息', icon: 'none' });
      return;
    }

    const targetId = `message-${index}`;
    wx.showToast({ title: '正在定位...', icon: 'none', duration: 500 });

    setTimeout(() => {
      this.setData({
        scrollToMessageId: targetId
      });
      const query = wx.createSelectorQuery();
      query.select(`#${targetId}`).boundingClientRect();
      query.exec((res) => {
        if (!res || !res[0]) {
          this.scrollToExistingMessage(index, retryCount - 1);
        }
      });
    }, 300);
  },

  simplify() {
    wx.showToast({ title: '简化功能待实现', icon: 'none' });
  },

  deepDive() {
    const theme = this.data.conversation.title || '人工智能';
    const question = `请深入讲解${theme}的核心概念和应用场景`;
    this.setData({
      showInitialPath: false // 进阶探索时隐藏初始路径
    });
    this.handleQuestion(question);
  },

  onInteractiveItemClick(e) {
    const selectedItem = e.currentTarget.dataset.item;
    this.setData({
      showInitialPath: false // 点击基础知识项时隐藏初始路径
    });
    this.handleQuestion(selectedItem);
  },

  onKnowledgeItemClick(e) {
    const selectedItem = e.currentTarget.dataset.item;
    this.setData({
      showInitialPath: false // 点击知识项时隐藏初始路径
    });
    this.handleQuestion(selectedItem);
    this.setData({ showMapPopup: false });
  },

  onRecommendedQuestionClick(e) {
    const selectedItem = e.currentTarget.dataset.item;
    this.setData({
      showInitialPath: false // 点击推荐问题时隐藏初始路径
    });
    this.handleQuestion(selectedItem);
  },

  hideHintPopup() {
    this.setData({ showHintPopup: false });
  },

  stopPropagation() {},

  getMessages: function() {
    const baseUrl = getApp().getApiBaseUrl();
    wx.request({
      url: `${baseUrl}/conversation/messages/${this.data.conversationID}`,
      method: 'GET',
      data: { unionID: this.data.unionID },
      success: res => {
        if (res.data.success) {
          const messages = res.data.messages.map(msg => ({
            ...msg,
            messageID: msg.messageID
          }));
          this.setData({
            messages,
            showInitialPath: messages.length === 0 // 更新消息后根据是否有消息控制初始路径
          });
        }
      }
    });
  },

  onTestOptionClick(e) {
    const { messageIndex, option, questionIndex } = e.currentTarget.dataset;
    const messages = this.data.messages;
    const testQuestion = messages[messageIndex].testQuestions[questionIndex];
  
    if (testQuestion.isCorrect) {
      wx.showToast({ title: '已答正确，无法再次答题', icon: 'none' });
      return;
    }
  
    let selectedOption = option;
    if (option.includes('.')) {
      selectedOption = option.split('.')[0].trim();
    } else {
      selectedOption = option.trim();
    }
  
    if (!selectedOption) {
      wx.showToast({ title: '选项数据错误', icon: 'none' });
      return;
    }
  
    const isCorrect = selectedOption === testQuestion.correctAnswer;
    const updatedTestQuestion = {
      ...testQuestion,
      selectedOption: selectedOption,
      resultStatus: isCorrect ? 'correct' : 'incorrect',
      feedback: isCorrect ? '回答正确！' : '回答错误，请再试一次。',
      isCorrect: isCorrect
    };
  
    // 创建新的 messages 数组，确保不可变性
    const updatedMessages = messages.map((msg, idx) => {
      if (idx === messageIndex) {
        return {
          ...msg,
          testQuestions: msg.testQuestions.map((tq, qIdx) =>
            qIdx === questionIndex ? updatedTestQuestion : tq
          )
        };
      }
      return msg;
    });
  
    this.setData({
      messages: updatedMessages
    });
  
    this.recordTestResult({
      messageIndex,
      questionIndex,
      selectedOption,
      isCorrect,
      messageID: messages[messageIndex].messageID
    });
  },

  recordTestResult({ messageIndex, questionIndex, selectedOption, isCorrect, messageID }) {
    const message = this.data.messages[messageIndex];
    const testQuestion = message.testQuestions[questionIndex];
    const unionID = this.data.unionID;

    if (!unionID || !messageID || !testQuestion.stem || !selectedOption) {
        console.error('缺少必要参数:', { unionID, messageID, question: testQuestion.stem, selectedOption });
        wx.showToast({ title: '数据缺失', icon: 'none' });
        return;
    }

    if (!/^[0-9a-fA-F]{24}$/.test(messageID)) {
        console.error('无效的 messageID 格式:', { messageIndex, questionIndex, messageID });
        wx.showModal({
            title: '提示',
            content: '消息数据异常，请重新加载对话',
            confirmText: '重新加载',
            success: (res) => {
                if (res.confirm) {
                    this.loadConversation();
                }
            }
        });
        return;
    }

    const jwtToken = wx.getStorageSync('jwt_token');
    if (!jwtToken) {
        console.error('缺少 JWT 令牌');
        wx.showModal({
            title: '提示',
            content: '请重新登录',
            success: (res) => {
                if (res.confirm) {
                    wx.redirectTo({ url: '/pages/login/login' });
                }
            }
        });
        return;
    }

    const requestData = {
        unionID: unionID,
        messageID: messageID,
        question: testQuestion.stem,
        answerTime: new Date().toISOString(),
        selectedOption: selectedOption,
        result: isCorrect,
        conversationID: this.data.conversationID
    };

    console.log('提交测试数据:', requestData);
    const baseUrl = getApp().getApiBaseUrl();
    wx.request({
      url: `${baseUrl}/conversation/record_test_result`,
        method: 'POST',
        data: JSON.stringify(requestData),
        header: {
            'Authorization': `Bearer ${jwtToken}`,
            'Content-Type': 'application/json'
        },
        success: (res) => {
            console.log('recordTestResult response:', res.data);
            if (res.statusCode === 200 && res.data.success) {
                console.log('测试结果提交成功:', res.data);
                setTimeout(() => this.loadConversation(), 1000);
            } else {
                console.error('提交失败，错误详情:', res.data);
                let errorMsg = res.data.detail || '记录测试结果失败';
                if (res.statusCode === 400) {
                    errorMsg = '提交数据无效，请检查问题或重新加载';
                } else if (res.statusCode === 403) {
                    errorMsg = '此问题已答对，无法重复提交';
                }
                wx.showModal({
                    title: '提交失败',
                    content: errorMsg,
                    confirmText: '重新加载',
                    cancelText: '取消',
                    success: (res) => {
                        if (res.confirm) {
                            this.loadConversation();
                        }
                    }
                });
            }
        },
        fail: (err) => {
            console.error('网络请求失败:', { messageIndex, questionIndex, err });
            wx.showToast({ title: '网络错误，请稍后重试', icon: 'none' });
        }
    });
},

  goToHistory() {
    wx.navigateTo({ url: '/pages/conversationHistory/conversationHistory' });
  },

  showAllQuestionsPopup() {
    this.setData({ showAllQuestionsPopup: true });
  },

  hideAllQuestionsPopup() {
    this.setData({ showAllQuestionsPopup: false });
  },

  onQuestionItemClick(e) {
    const index = e.currentTarget.dataset.index;
    this.scrollToExistingMessage(index);
    this.hideAllQuestionsPopup();
  },
  // 用户点击右上角菜单中的“转发”
  onShareAppMessage() {    
    const title = this.data.conversation.title || '学习导航';
    const conversationID = this.data.conversationID || '';
    const unionID = wx.getStorageSync('unionID') || '';
    const subjectDisplay = this.getSubjectDisplay(this.data.subject);
    const sharePath = unionID
      ? `/pages/conversation/conversation?conversationID=${conversationID}&inviterID=${encodeURIComponent(unionID)}`
      : `/pages/conversation/conversation?conversationID=${conversationID}`;
  
    if (!unionID) {
      wx.showToast({ title: '登录后分享可获得推荐奖励', icon: 'none' });
    }
  
    return {
      title: `[${subjectDisplay}] ${title}`,
      path: sharePath
    };
  },

  // 用户点击右上角菜单中的“分享到朋友圈”
  onShareTimeline() {    
    const title = this.data.conversation.title || '学习导航';
    const conversationID = this.data.conversationID || '';
    const unionID = wx.getStorageSync('unionID') || '';
    const subjectDisplay = this.getSubjectDisplay(this.data.subject);
    const query = unionID
      ? `conversationID=${conversationID}&inviterID=${encodeURIComponent(unionID)}`
      : `conversationID=${conversationID}`;
  
    return {
      title: `[${subjectDisplay}] ${title}`,
      query: query
    };
  }
});